package com.wzx.user.controller;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.wzx.common.exception.LeadNewsException;
import com.wzx.common.pojo.resp.Result;
import com.wzx.user.pojo.shop.vo.ReleaseDynamicVo;
import com.wzx.user.service.PayZfbService;
import com.wzx.user.vo.PayVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/6/8 - 21:32
 * @description 标题
 */
@Slf4j
@RestController
@RequestMapping("/payZfb")
public class PayZfbController {

    @Autowired
    private PayZfbService payZfbService;

    @ApiOperation(value = "支付宝充值")
    @PostMapping("/userRechargeAmount")
    public Result<String> userRechargeAmount(@RequestBody PayVo payVo) throws AlipayApiException, LeadNewsException {
        String response = payZfbService.userRechargeAmount(payVo);
        return Result.ok(response);
    }

    //网络异常信息:Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
    @ApiOperation(value = "充值回调")
    @PostMapping("/userRechargeCallback")
    public String userRechargeCallback(@RequestParam Map<String, Object> map) throws AlipayApiException, LeadNewsException {
        //我的接口（APP支付TRADE_SUCCESS（交易成功）、TRADE_CLOSED（交易关闭）、TRADE_FINISHED（交易完成）三种状态均会触发异步通知）
        log.info("支付宝支付回调通知：{}", map.toString());
        try {
            String tradeStatus = (String) map.get("trade_status");
            String outTradeNo = (String) map.get("out_trade_no");

            //充值成功
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                payZfbService.tradeStatusOk(outTradeNo);
            } else {
                payZfbService.tradeStatusError(outTradeNo);
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
            log.error("充值信息解析异常！");
        }

        /*{gmt_create=2023-06-09 14:44:27,
                charset=UTF-8,
                seller_email=793161468@qq.com, s
                ubject=用户下订单,
                sign=TtkN40N/zZCD8eCvZsl8Y9VmYMxojmcJEDt74qHqWl0wwizkkAhwcu9ANUaS9Oi1CPdOhz0wKmP4pEICM8KLOhjUC1g/QTasazHftQDvrsOKr5ag7IVc8r0PfBKvwk0N+9M/STud2ZjoVO5NxtX+w7oPPE9Bf6mhAmEigCJYE2m7N5kWdPCcaq6h9hbfr/z7lDJFQPa7P4qe8HUda4X/Pon5NLbV60anvC/Md6a7T94Z7U3Leh76Eicq6TWvgTZpNNRlRO7uWR/iWWPGJAHzP06vyXk1AC8Tdg+HakG+niDCyhiPfnxEYVliFpjhpfjJKoWsElePMnxIYVb+tH22GQ==,
                buyer_id=2088822046795485,
                invoice_amount=0.01,
                notify_id=2023060901222144427095481483273851,
                fund_bill_list=[
                        {"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}],
                notify_type=trade_status_sync,
                trade_status=TRADE_SUCCESS,
                        receipt_amount=0.01,
                        app_id=2021003181612006,
                        buyer_pay_amount=0.01,
                        sign_type=RSA2,
                        seller_id=2088441932788941,
                        gmt_payment=2023-06-09 14:44:27,
                notify_time=2023-06-09 14:44:28,
                version=1.0,
                out_trade_no=1607,
                total_amount=0.01,
                trade_no=2023060922001495481456197871,
                auth_app_id=2021003181612006,
                buyer_logon_id=188****3360,
                point_amount=0.00}
        map = {gmt_create=2023-06-09 14:44:27,
                charset=UTF-8,
                seller_email=793161468@qq.com,
                subject=用户下订单,
                sign=TtkN40N/zZCD8eCvZsl8Y9VmYMxojmcJEDt74qHqWl0wwizkkAhwcu9ANUaS9Oi1CPdOhz0wKmP4pEICM8KLOhjUC1g/QTasazHftQDvrsOKr5ag7IVc8r0PfBKvwk0N+9M/STud2ZjoVO5NxtX+w7oPPE9Bf6mhAmEigCJYE2m7N5kWdPCcaq6h9hbfr/z7lDJFQPa7P4qe8HUda4X/Pon5NLbV60anvC/Md6a7T94Z7U3Leh76Eicq6TWvgTZpNNRlRO7uWR/iWWPGJAHzP06vyXk1AC8Tdg+HakG+niDCyhiPfnxEYVliFpjhpfjJKoWsElePMnxIYVb+tH22GQ==,
                buyer_id=2088822046795485, invoice_amount=0.01, notify_id=2023060901222144427095481483273851, fund_bill_list=[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}], notify_type=trade_status_sync, trade_status=TRADE_SUCCESS, receipt_amount=0.01, app_id=2021003181612006, buyer_pay_amount=0.01, sign_type=RSA2, seller_id=2088441932788941, gmt_payment=2023-06-09 14:44:27, notify_time=2023-06-09 14:44:28, version=1.0, out_trade_no=1607, total_amount=0.01, trade_no=2023060922001495481456197871, auth_app_id=2021003181612006, buyer_logon_id=188****3360, point_amount=0.00}
        log.info(map.toString());*/
        //String response = payZfbService.userRechargeAmount(payVo);
        return "success";
    }

    @ApiOperation(value = "用户支付宝创建订单")
    @PostMapping("/userRechargeOrder")
    public Result<String> userRechargeOrder(@RequestBody PayVo payVo) throws AlipayApiException, LeadNewsException {
        String response = payZfbService.userRechargeOrder(payVo);
        return Result.ok(response);
    }


    @ApiOperation(value = "订单回调")
    @PostMapping("/userRechargeCallbackByOrder")
    public String userRechargeCallbackByOrder(@RequestParam Map<String, Object> map) throws AlipayApiException, LeadNewsException {
        //我的接口（APP支付TRADE_SUCCESS（交易成功）、TRADE_CLOSED（交易关闭）、TRADE_FINISHED（交易完成）三种状态均会触发异步通知）
        log.info("支付宝订单回调通知：{}", map.toString());
        try {
            String tradeStatus = (String) map.get("trade_status");
            String outTradeNo = (String) map.get("out_trade_no");

            //充值成功
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                payZfbService.tradeStatusOrderOk(outTradeNo);
            } else {
                payZfbService.tradeStatusOrderError(outTradeNo);
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
            log.error("充值信息解析异常！");
        }

        return "success";
    }

    @ApiOperation(value = "用户支付宝发布商品")
    @PostMapping("/userReleaseByZfb")
    public Result<String> userReleaseByZfb(@RequestBody ReleaseDynamicVo releaseDynamicVo) throws AlipayApiException, LeadNewsException {
        String response = payZfbService.userReleaseByZfb(releaseDynamicVo);
        return Result.ok(response);
    }

    @ApiOperation(value = "订单回调")
    @PostMapping("/userReleaseByZfbCallback")
    public String userReleaseByZfbCallback(@RequestParam Map<String, Object> map) throws AlipayApiException, LeadNewsException {
        //我的接口（APP支付TRADE_SUCCESS（交易成功）、TRADE_CLOSED（交易关闭）、TRADE_FINISHED（交易完成）三种状态均会触发异步通知）
        log.info("支付宝发布动态回调通知：{}", map.toString());
        try {
            String tradeStatus = (String) map.get("trade_status");
            String outTradeNo = (String) map.get("out_trade_no");

            //充值成功
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                payZfbService.userReleaseByZfbCallbackOk(outTradeNo);
            } else {
                payZfbService.userReleaseByZfbCallbackError(outTradeNo);
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
            log.error("支付宝发布动态回调通知信息解析异常！");
        }

        return "success";
    }


    @ApiOperation(value = "支付宝绑定")
    @PostMapping("/userBindingZfb")
    public Result userBindingZfb(@RequestBody PayVo payVo) throws AlipayApiException, LeadNewsException {
        payZfbService.userBindingZfb(payVo.getUserId(), payVo.getAuthCode());
        return Result.ok();
    }


}
